package clei.sample

import android.arch.paging.PageKeyedDataSource
import android.os.Handler
import android.os.Looper
import android.util.Log
import kotlin.coroutines.experimental.buildSequence
import kotlin.math.log

/**
 *  create by chenglei at 2018/10/23
 */


class LanguageDataSource: PageKeyedDataSource<Int, Language>() {
    override fun loadInitial(params: LoadInitialParams<Int>, callback: LoadInitialCallback<Int, Language>) {
        Log.e(javaClass.simpleName, "loadInitial, in ${Thread.currentThread().name}")
//        callback.onResult(listOf(1,2,3,4,5,6,7,8,9,10,11,12,13,14,15)
//                .mapIndexed { index, _ ->
//                    Language("test", "test", index)
//                }.toList().apply { Log.e(javaClass.simpleName, "size: $size")}, null, 1)

        LanguageRepository.requestLanguages({datas->
            if (datas.code == 200) {
                val languages = datas.data
                Log.e(javaClass.simpleName, "languages size: ${languages.size}")
                Handler(Looper.getMainLooper()).post {
                    callback.onResult(languages, null, 1)
                }
            } else {
                Log.e(javaClass.simpleName, "response code is not 200")
            }
        }, {t->
            Log.e(javaClass.simpleName, "${t.message}")
        })

//        val list = LanguageRepository.requestLanguagesSync()
//        callback.onResult(list, null, 1)
    }

    override fun loadAfter(params: LoadParams<Int>, callback: LoadCallback<Int, Language>) {
        Log.e(javaClass.simpleName, "loadAfter in ${Thread.currentThread().name}")
        callback.onResult(listOf(1,2,3,4,5,6,7,8,9,10,11,12,13,14,15)
                .mapIndexed { index, _ ->
                    Language("test", "test", index)
                }.toList().apply { Log.e(javaClass.simpleName, "size: $size")}, params.key+1)
    }

    override fun loadBefore(params: LoadParams<Int>, callback: LoadCallback<Int, Language>) {
    }

}